package com.leetcode.partition3;

import java.util.HashSet;
import java.util.Set;

/**
 * @author `RKC`
 * @date 2021/9/9 12:33
 */
public class LC202快乐数 {

    public static boolean isHappy(int n) {
        return hashtable(n);
    }

    public static void main(String[] args) {
        System.out.println(isHappy(2));
    }

    private static boolean hashtable(int n) {
        Set<Integer> ht = new HashSet<>();
        while (true) {
            n = getNextNumber(n);
            if (n == 1) return true;
            if (ht.contains(n)) {          //当前数字进入了无限循环
                return false;
            }
            ht.add(n);
        }
    }

    private static int getNextNumber(int n) {
        int res = 0;
        while (n != 0) {
            int t = n % 10;
            res += t * t;
            n /= 10;
        }
        return res;
    }
}
